package com.dhf.framework.common.interceptors;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.dhf.framework.common.Constants;
import com.dhf.framework.system.entity.SysUser;


/**
 * 
* @ClassName: AuthInterceptor
* @Description: 权限拦截器
* @author HoraceHo
*
 */
public class AuthInterceptor implements HandlerInterceptor {	 
    private static Logger LOGGER = LoggerFactory.getLogger(AuthInterceptor.class);  
	private List<String> excludeUrls;
	public List<String> getExcludeUrls() {
		return excludeUrls;
	}
	public void setExcludeUrls(List<String> excludeUrls) {
		this.excludeUrls = excludeUrls;
	}
	/**
	 * 在controller后拦截
	 */
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) throws Exception {
	    
	}
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView) throws Exception {

	}
	/**
	 * 在controller前拦截
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		String requestPath = request.getServletPath();// 用户访问的资源地址
		LOGGER.info(requestPath);
		if(requestPath.contains("resources")){  //放行
		    return true;
		}else if(pathMatcher(excludeUrls,requestPath)) {  //放行
			return true;
		}else {
		    SysUser sysUser=(SysUser) request.getSession().getAttribute(Constants.SESSION_USER_KEY);
		    //如果前端Session域没有用户信息，拦截器拦截
		    if(sysUser==null){
		        response.sendRedirect(request.getContextPath()+"/login.do");
	            return false;
		    }else{
		        return true;
		    }
		}
	}
	
	/**
	 * 模糊匹配字符串
	 * @param list
	 * @param key
	 * @return
	 */
	private boolean pathMatcher(List<String> list,String key){
	    PathMatcher  matcher = new AntPathMatcher();
		for(String str : list){
			if(matcher.match(str, key)){
				return true;
			}
		}
		return false;
	}
}
